<!--
 * @Author: 陈俊升 761723995@qq.com
 * @Date: 2024-01-12 10:55:28
 * @LastEditors: 陈俊升 761723995@qq.com
 * @LastEditTime: 2024-02-18 13:42:42
 * @FilePath: /hr_new_vue3/src/components/HumanOrDepartmentModal/index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!-- 选择人员和部门弹出框，用来选择人员和部门 -->
<template>
  <a-modal
    :width="600"
    :visible="visible"
    @ok="handleOk"
    @cancel="handleCancel"
    :mask-closable="false"
    title-align="center"
    unmount-on-close
    :body-style="{
      padding: '0px'
    }"
  >
    <template #title>
      <div>选择部门与人员</div>
    </template>
    <div class="wrap">
      <div class="left">
        <a-input-search
          placeholder="请输入"
          v-model="nameSearch"
          search-button
        ></a-input-search>

        <a-breadcrumb>
          <template #separator>
            <icon-right />
          </template>
          <a-breadcrumb-item v-for="(item, index) in breadcrumb" :key="index">
            {{ item }}
          </a-breadcrumb-item>
        </a-breadcrumb>

        <a-tree
          :checkable="true"
          v-model:checked-keys="checkedKeys"
          v-model:expanded-keys="expandedKeys"
          :data="organizationList"
          :fieldNames="{
            key: 'id',
            title: 'name',
            children: 'children'
          }"
          :check-strictly="true"
          @select="treeSelect"
          @check="treeChange"
        />

        <a-checkbox-group
          direction="vertical"
          v-model="humanCheckedKeys"
          @change="checkChange"
        >
          <a-checkbox v-for="item in humanList" :key="item.id" :value="item.id">
            <a-avatar>
              <img alt="avatar" :src="item.headPortrait" />
            </a-avatar>
            {{ item.name }}
          </a-checkbox>
        </a-checkbox-group>
      </div>
      <div class="right">
        <div class="clear">
          <a-button type="text" @click="cleanAll">全部清空</a-button>
        </div>
        <div
          v-for="(item, index) in formData.data.info"
          :key="item.id"
          class="selected-item"
        >
          <div>
            <a-avatar>
              <img alt="avatar" :src="item.headPortrait" />
            </a-avatar>
            <span>{{ item.name }}</span>
          </div>
          <icon-close class="icon" @click="remove(item, index)" />
        </div>
      </div>
    </div>
  </a-modal>
</template>

<script lang="tsx" setup>
import { controldataTreeFilter, flatTree } from '@/utils/utils';
import {
  GetHumanRosterList,
  GetOrganizationHuman
} from '@/apis/management/human/humanRoster';
import { GetOrganizationList } from '@/apis/management/organization/organizationManagement';
import { cloneDeep } from 'lodash';
const props = withDefaults(
  defineProps<{
    visible: boolean; // 是否显示对话框，
    data: any;
  }>(),
  {
    visible: false
  }
);

const emit = defineEmits(['update:visible', 'humanOrDepartmentEmit']);

const formData = reactive({
  data: {
    info: []
  }
});
const checkedKeys = ref([]); // 部门选择的keys
let humanCheckedKeys = ref([]); // 储存选中的人员的ids

watch(
  () => props.visible,
  (newVal: boolean) => {
    if (newVal) {
      if (props.data?.length > 0) {
        reset();
        formData.data.info = cloneDeep(props.data);
        formData.data.info.forEach((el: any) => {
          if (el.type === 1) {
            checkedKeys.value.push(el.id);
          } else {
            humanCheckedKeys.value.push(el.id);
          }
        });
        preSelectedTreeLen = checkedKeys.value.length;
        preSelectedLen = humanCheckedKeys.value.length;
      } else {
        reset();
      }
      console.log(
        '==========formDataformDataformData=========================='
      );
      console.log(props.data);
      console.log('====================================');
    }
  }
);

let organizationList = ref([]); // 公司列表
let flatOrganizationList = ref([]); // 扁平化的公司列表

let expandedKeys = ref([]);

let humanList = ref([]); // 部门下的人员

const getData = async () => {
  try {
    const [organizationListRes] = await Promise.all([GetOrganizationList({})]);
    flatOrganizationList.value = flatTree(organizationListRes);
    expandedKeys.value = flatTree(organizationListRes).map((el: any) => el.id);
    organizationList.value = dealTreeData(organizationListRes);
  } catch (error: unknown) {
    console.log(error);
  }
};
getData();

// 重新组合树数据(根据需要来重组树结构中的属性字段，用来新增判断是否为叶子节点信息)
const dealTreeData = (treeData: any) => {
  const data = treeData.map((item: any) => ({
    ...item,
    ...controldataTreeFilter(item.ctlValue),
    // 新增叶子节点字段
    // isLeaf: item.children ? false : true,
    disabled: item.node === '公司',
    // 新增是否能被选中字段，默认只有叶子节点可以选
    // selectable: item.children ? false : true,
    // 如果children为空数组，则置为null
    children:
      item.children && item.children.length ? dealTreeData(item.children) : null
  }));
  return data;
};

const breadcrumb = ref([]);

// 获取面包屑
const getBreadcrumb = (id: number) => {
  const node = flatOrganizationList.value.find((el) => el.id === id);
  if (node) {
    breadcrumb.value = [node.name, ...breadcrumb.value];
    if (node.superiorId) {
      getBreadcrumb(node.superiorId);
    }
  }
};

const treeSelect = async (selectedKeys: [], data: any) => {
  try {
    const res = await GetOrganizationHuman({
      typeName: '部门',
      id: data.node.id,
      pageNumber: 0,
      pageSize: -1
    });
    humanList.value = res.content;
    breadcrumb.value = [];
    getBreadcrumb(data.node.id);
  } catch (error: unknown) {
    console.log(error);
  }
};

let preSelectedTreeLen = 0; // 储存上一次选中的长度
let preSelectedTreeIds = []; // 储存上一次选中的ids
const treeChange = (checkedKeys: [], data: any) => {
  if (checkedKeys.length > preSelectedTreeLen) {
    formData.data.info.push({
      name: data.node.name,
      id: data.node.id,
      headPortrait: data.node.headPortrait,
      type: 1,
      uid: `${data.node.id}-1` // 唯一标识, 部门后缀为1
    });
  } else {
    // 判断取消选中的项目逻辑...
    const removedId = preSelectedTreeIds.find(
      (id) => !checkedKeys.includes(id)
    );
    if (removedId) {
      // 在 preSelectedIds 中找到不在 checked 中的 ID
      // 执行取消选中的项目逻辑...
      const removedItemIndex = formData.data.info.findIndex(
        (item) => item.id === removedId
      );
      if (removedItemIndex !== -1) {
        formData.data.info.splice(removedItemIndex, 1);
      }
    }
  }
  preSelectedTreeLen = checkedKeys.length;
  preSelectedTreeIds = checkedKeys;
};

let preSelectedLen = 0; // 储存上一次选中的长度
let preSelectedIds = []; // 储存上一次选中的ids
const checkChange = (checked: any) => {
  // 新增一个人员
  if (checked.length > preSelectedLen) {
    const temp = humanList.value.find(
      (el: any) => el.id === checked[checked.length - 1]
    );
    formData.data.info.push({
      name: temp.name,
      id: temp.id,
      headPortrait: temp.headPortrait,
      type: 2,
      uid: `${temp.id}-2` // 唯一标识, 人员后缀为2
    });
  }
  // 取消勾选一个人
  else {
    // 判断取消选中的项目逻辑...
    const removedId = preSelectedIds.find((id) => !checked.includes(id));
    if (removedId) {
      // 在 preSelectedIds 中找到不在 checked 中的 ID
      // 执行取消选中的项目逻辑...
      const removedItemIndex = formData.data.info.findIndex(
        (item) => item.id === removedId
      );
      if (removedItemIndex !== -1) {
        formData.data.info.splice(removedItemIndex, 1);
      }
    }
  }
  preSelectedLen = checked.length;
  preSelectedIds = checked;
};

// 去除一项
const remove = (record: any, ind: number) => {
  if (record.type === 1) {
    checkedKeys.value = checkedKeys.value.filter(
      (item: any) => item !== record.id
    );
  } else {
    humanCheckedKeys.value = humanCheckedKeys.value.filter(
      (item: any) => item !== record.id
    );
  }
  formData.data.info.splice(ind, 1);
};

// 全部清空
const cleanAll = () => {
  checkedKeys.value = [];
  humanCheckedKeys.value = [];
  formData.data.info = [];
};

// 保存
const handleOk = () => {
  // const temp = cloneDeep(
  //   selectedListData.value[selectedListData.value.length - 1]
  // );

  // emit('humanRosterEmit', temp);
  // 清空选择器
  // tableRef.value.selectedListData = [];
  // tableRef.value.selectedList = [];
  // modalVisible.value = false;
  emit('humanOrDepartmentEmit', formData.data.info);
  emit('update:visible', false);
};

// 取消
const handleCancel = () => {
  // 清空选择器
  // tableRef.value.selectedListData = [];
  // tableRef.value.selectedList = [];
  // modalVisible.value = false;
  emit('update:visible', false);
};

const reset = () => {
  checkedKeys.value = [];
  humanCheckedKeys.value = [];
  formData.data.info = [];
  preSelectedTreeLen = 0;
  preSelectedLen = 0;
};
</script>

<style scoped lang="less">
.wrap {
  min-height: 500px;
  height: 100%;
  max-height: 600px;
  display: flex;

  .left,
  .right {
    padding: 10px;
    width: 50%;
  }

  .left {
    height: 100%;
    // border-right: 1px solid #ccc;
    border-width: 0 1px 0 0;
    border-style: solid;
    border-color: #eee;
  }

  .right {
    .clear {
      margin-bottom: 10px;
      text-align: right;
    }
    .selected-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 5px;
      width: 100%;
      height: 50px;
      padding: 0 10px 0 0;
      background-color: #eee;
      line-height: 50px;

      .icon {
        cursor: pointer;
      }
    }
  }
}
</style>
